/*
 * @Author: yangzonglong
 * @Date: 2021-06-30 14:57:27
 * @version: v1.0.0
 * @Descripttion: 上传控件
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-12-02 14:19:31
 * @Auditor:
 */
import React, { useImperativeHandle, forwardRef, useRef, useState, useEffect } from 'react';
import { Form } from 'antd';
import Jodit, { JoditRef } from './Jodit';
import useQueryControlWrap from '../../hooks/useQueryControlWrap';
import { CanvasItemProps } from './../../interface';
import { FormItemProps } from '../../components/components/InputFormItemController';
import 'jodit/build/jodit.min.css';
interface RefProps {
  getData(): any;
}

export interface RichProps extends CanvasItemProps {
  richInitialValue?: string;
  formItemProps?: FormItemProps;
  disabled?: boolean;
  style?: React.CSSProperties;
  preview?: boolean;
}

const ComponentUpload = (props: RichProps, ref: React.Ref<RefProps>) => {
  const { disabled, formItemProps, domComplete, preview, richInitialValue, initialValue: _initialValue, ...canvasProps } = props;
  const joditRef = useRef<JoditRef>(null);
  const [initialValue, setInitialValue] = useState<any>(null);

  useQueryControlWrap(canvasProps.id, formItemProps?.name, domComplete);

  useImperativeHandle(ref, () => ({
    getData() {
      console.log(joditRef.current?.getValue());

      return joditRef.current?.getValue() || initialValue;
    },
    setData(v: any) {
      setInitialValue(v);
    },
  }));

  useEffect(() => {
    if (_initialValue) {
      setInitialValue(_initialValue);
    }
  }, [_initialValue]);

  const label = localStorage.i18nextLng === 'en' ? formItemProps?.labelEn : formItemProps?.label;

  return (
    <Form.Item {...canvasProps} {...props.formItemProps} label={label} >
      <div style={{ overflowX: 'auto' }}>
        {disabled || formItemProps?.disabled || preview ? (
          <div className={'jodit-wysiwyg'} dangerouslySetInnerHTML={{ __html: initialValue || richInitialValue || '' }} />
        ) : (
          <Jodit
            ref={joditRef}
            initialValue={initialValue || richInitialValue}
            height={canvasProps.isDesign ? 60 : 300} />
        )}
      </div>
    </Form.Item>
  );
};

export default forwardRef(ComponentUpload);
